<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品清单管理
 *
 * @icon fa fa-circle-o
 */
class Listo extends Backend
{

    /**
     * Listo模型对象
     * @var \app\admin\model\product\Listo
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\product\Listo;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        $param = $this->request->param();
        $this->assignconfig('order_id', $param['order_id']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where_str = '';
            if ($param['order_id']) {
                $where_str = 'listo.order_id = ' . $param['order_id'];
            }

            $list = $this->model
                ->with(['order'])
                ->where($where)
                ->where($where_str)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('order')->visible(['order_id', 'is_trans', 'status']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 发货
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function send($ids = null)
    {
        if (false === $this->request->isPost()) {

            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
            }

            $id = $params['id'];
            $list = $this->model->where('id', $id)->find();
            if ($list['status'] != 1) {
                $this->error('该订单不可发货！');
            }

            $list->tool = $params['tool'];
            $list->send_name = $params['send_name'];
            $list->send_contact = $params['send_contact'];
            $list->send_address = $params['send_address'];
            $list->status = 10;
            $list->toolid = $params['toolid'];
            $list->send_time = time();

            $result = $list->save();

            $num = $this->model->where('order_id', $list['order_id'])->where('status', 'lt', 10)->count();
            if ($num == 0) {
                \app\admin\model\product\Order::where('id', $list['order_id'])->update(['status' => 10, 'send_time' => time()]);
            }

            Db::commit();
        } catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('发货成功', url('product/order'));
    }
}
